package com.gdyx.app.web.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gdyx.app.web.annotation.Authorisation;
import com.gdyx.app.web.dto.ZTreeNode;
import com.gdyx.app.web.model.*;
import com.gdyx.app.web.svc.*;
import com.gdyx.app.web.util.Condition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by Y_Coffee on 2017/8/4.
 */
@Controller
@RequestMapping("/MpsFun")
@Scope("prototype")
public class MpsFunController extends BaseController {
    @Autowired
    HttpServletRequest request;
    @Autowired
    MpsFunSvc mpsFunSvc;
    @Autowired
    MpsRoleFunSvc mpsRoleFunSvc;
    @Autowired
    MpsFunOptSvc mpsFunOptSvc;
    @Autowired
    MpsRoleOptSvc mpsRoleOptSvc;
    @Autowired
    MpsUserRoleSvc mpsUserRoleSvc;
    @Autowired
    MpsDeptUserSvc mpsDeptUserSvc;
    @Autowired
    MpsDeptRoleSvc mpsDeptRoleSvc;


    @Authorisation(value = "/MpsFun/goMpsFunList")
    @GetMapping("/goMpsFunList")
    public ModelAndView goMpsFunList(@ModelAttribute("respMsg") String respMsg) {
        ModelAndView view = new ModelAndView();
        Map<String, Object> map = new HashMap<>();
        map.put("order", "order by parent");
        List<MpsFun> list = mpsFunSvc.findMpsFuns(map);
        List<MpsFun> det = new ArrayList<>();
        DoRoot(list, det);
        //JSONArray array= JSON.
        view.addObject("MpsFunList", det);
        view.addObject("respMsg", respMsg);
        view.setViewName("MpsFunList");
        return view;
    }

    @Authorisation(value = "/MpsFun/Save")
    @GetMapping("goMpsFunAdd")
    public ModelAndView goMpsFunAdd(@ModelAttribute("respMsg") String respMsg) {
        ModelAndView view = new ModelAndView();
        List<MpsFun> list = mpsFunSvc.findMpsFuns(new HashMap<>());
        //JSONArray array= JSON.
        view.addObject("MpsFunList", JSON.toJSONString(list));
        view.addObject("respMsg", respMsg);
        view.setViewName("MpsFunAdd");
        return view;
    }

    @Authorisation(value = "/MpsFun/Update")
    @GetMapping("goMpsFunEdit")
    public ModelAndView goMpsFunEdit(@ModelAttribute("respMsg") String respMsg, @RequestParam("id") String id) {
        ModelAndView view = new ModelAndView();
        List<MpsFun> list = mpsFunSvc.findMpsFuns(new HashMap<>());
        //JSONArray array= JSON.
        view.addObject("MpsFunList", JSON.toJSONString(list));
        MpsFun mpsFun = mpsFunSvc.findMpsFunById(id);
        view.addObject("F_I", mpsFun);
        view.addObject("respMsg", respMsg);
        view.setViewName("MpsFunEdit");
        return view;
    }

    @Authorisation(value = "/MpsFun/Save")
    @PostMapping("Save")
    public String save(RedirectAttributes attr, MpsFun o) {
        if (StringUtils.isEmpty(o.getName())) {
            attr.addFlashAttribute("respMsg", "操作失败，功能名称不能为空");
            return "redirect:/MpsFun/goMpsFunAdd";
        }
        Map<String, Object> map = new HashMap<>();
        List<Condition> conditions = new ArrayList<>();
        conditions.add(ruleBuild("and", "name", "=", o.getName(), "S"));
        map.put("conditions", conditions);
        int count = mpsFunSvc.count(map);
        if (count > 0) {
            attr.addFlashAttribute("respMsg", "操作失败，功能名称已存在");
            return "redirect:/MpsFun/goMpsFunAdd";
        }
        o.setId(UUID.randomUUID().toString().toUpperCase().trim());
        mpsFunSvc.save(o);
        attr.addFlashAttribute("respMsg", "增加功能：" + o.getName() + "成功");
        return "redirect:/MpsFun/goMpsFunList";
    }

    @Authorisation(value = "/MpsFun/Delete")
    @GetMapping("Delete")
    public String delete(RedirectAttributes attr, @RequestParam("id") String id) {
        try {
            Map<String, Object> map = new HashMap<>();
            List<Condition> conditions = new ArrayList<>();
            conditions.add(ruleBuild("and", "parent", "=", id, "S"));
            map.put("conditions", conditions);
            int count = mpsFunSvc.count(map);
            if (count > 0) {
                attr.addFlashAttribute("respMsg", "操作失败，有子节点");
            } else {
                mpsFunSvc.delete(id);
                attr.addFlashAttribute("respMsg", "删除功能成功");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "redirect:/MpsFun/goMpsFunList";
    }

    @Authorisation(value = "/MpsFun/Update")
    @PostMapping("Update")
    public String update(RedirectAttributes attr, MpsFun o) {
        if (StringUtils.isEmpty(o.getName())) {
            attr.addFlashAttribute("respMsg", "操作失败，功能名称不能为空");
            return "redirect:/MpsFun/goMpsFunAdd";
        }
        Map<String, Object> map = new HashMap<>();
        List<Condition> conditions = new ArrayList<>();
        conditions.add(ruleBuild("and", "id", "<>", o.getId(), "S"));
        conditions.add(ruleBuild("and", "name", "=", o.getName(), "S"));
        map.put("conditions", conditions);
        int count = mpsFunSvc.count(map);
        if (count > 0) {
            attr.addFlashAttribute("respMsg", "操作失败，功能名称已存在");
            return "redirect:/MpsRole/goMpsRoleEdit?id=" + o.getId();
        }
        mpsFunSvc.update(o);
        attr.addFlashAttribute("respMsg", "更新功能：" + o.getName() + "成功");
        return "redirect:/MpsFun/goMpsFunList";
    }

    @GetMapping("AjaxMpsFun")
    @ResponseBody
    public String AjaxMpsFun() {
        List<MpsFun> list = mpsFunSvc.findMpsFuns(new HashMap<>());
        JSONArray array = new JSONArray();
        List<MpsFun> det = new ArrayList<>();
        DoRoot(list, det);
        det.stream().forEach(item -> {
            det.add(item);
        });
        return array.toString().replace("parent", "pId");
    }

    @Authorisation(value = "/MpsFun/setAuthority")
    @PostMapping("mpsAllFunByRoleId")
    @ResponseBody
    public String mpsAllFunByRoleId(String roleId) {
        List<ZTreeNode> resultList = new ArrayList<>();
        MpsUser nowMpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        //当前用户下权限
        List<MpsFun> allMpsFuns = new ArrayList<>();
        //当前用户下操作
        List<MpsFunOpt> allMpsOpts = new ArrayList<>();
        Set<String> allRoles = new HashSet<>();

        //当前用户的角色
        List<MpsRole> mpsRoles = GetRoleByUserAndOrg(nowMpsUser.getId(),org_session);
        mpsRoles.stream().forEach(role -> {
            allRoles.add(role.getId());
        });
        //当前用户的部门
        List<MpsDept> mpsDepts = GetDeptByUserAndOrg(nowMpsUser.getId(),org_session);
        mpsDepts.stream().forEach(dept -> {
            List<MpsDeptRole> mpsDeptRoleList = mpsDeptRoleSvc.findDeptRoleByDid(dept.getId());
            mpsDeptRoleList.stream().forEach(wdr -> {
                allRoles.add(wdr.getRoleId());
            });
        });
        //获取角色权限
        allRoles.stream().forEach(role -> getFunById(role).forEach(wrfa -> allMpsFuns.add(mpsFunSvc.findMpsFunById(wrfa.getFunId()))));
        //获取角色操作
        allRoles.stream().forEach(role -> getOptById(role).forEach(wrfa -> allMpsOpts.add(mpsFunOptSvc.findMpsFunOptById(wrfa.getOptId()))));
        //去重
        List<MpsFun> mpsFuns = new ArrayList<>(new HashSet<>(allMpsFuns));
        List<MpsFunOpt> mpsFunOpts = new ArrayList<>(new HashSet<>(allMpsOpts));
        //回显已有
        List<MpsRoleFun> oldFunById = this.getFunById(roleId);
        List<MpsRoleOpt> oldOptById = this.getOptById(roleId);
        //构建
        for (MpsFun mpsFun : mpsFuns) {
            ZTreeNode zTreeNode = new ZTreeNode();
            zTreeNode.setId(mpsFun.getId());
            zTreeNode.setpId(mpsFun.getParent());
            zTreeNode.setName(mpsFun.getName());
            for (MpsRoleFun mpsRoleFun : oldFunById) {
                if (mpsFun.getId().equals(mpsRoleFun.getFunId())) {
                    zTreeNode.setChecked(true);
                    zTreeNode.setIsOpen(true);
                }
            }
            resultList.add(zTreeNode);
        }
        for (MpsFunOpt mpsFunOpt : mpsFunOpts) {
            ZTreeNode zTreeNode = new ZTreeNode();
            zTreeNode.setId(mpsFunOpt.getId());
            zTreeNode.setpId(mpsFunOpt.getFunId());
            zTreeNode.setName(mpsFunOpt.getName());
            for (MpsRoleOpt mpsRoleOpt : oldOptById) {
                if (mpsRoleOpt.getOptId().equals(mpsFunOpt.getId())) {
                    zTreeNode.setChecked(true);
                }
            }
            resultList.add(zTreeNode);
        }

        return JSONObject.toJSONString(resultList);
    }

    @Authorisation(value = "/MpsFun/setAuthority")
    @PostMapping("setAuthority")
    @ResponseBody
    public String setAuthority(@RequestParam("roleId") String roleId, @RequestParam("ids") String ids) {
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        //拥有的权限
        List<MpsFun> mpsFunList = (List<MpsFun>) request.getSession().getAttribute("WEBFUNS");
        List<MpsFunOpt> mpsFunOptList = (List<MpsFunOpt>) request.getSession().getAttribute("WEBOPTS");
        //当前用户所属机构
        List<MpsOrgUser> mpsOrgUserList = mpsOrgUserSvc.findMpsOrgUsersByUid(mpsUser.getId());
        mpsFunSvc.setAuthority(roleId, ids, mpsUser.getId(), mpsFunList, mpsFunOptList);
        return "{\"status\":\"success\"}";
    }

    public List<MpsRoleFun> getFunById(String roleId) {
          /*
        依据roleId获取功能权限id
        */
        List<MpsRoleFun> mpsRoleFunAuths = null;
        try {
            //构建条件查询
            Map<String, Object> map = new HashMap<>();
            Condition condition = new Condition();
            condition.setConnector("and");
            condition.setColumn("roleId");
            condition.setOperator("=");
            condition.setType("S");
            condition.setValue(roleId);
            List<Condition> conditions = new ArrayList<>();
            conditions.add(condition);
            map.put("conditions", conditions);
            //依据关联表查询该角色拥有的功能权限
            mpsRoleFunAuths = mpsRoleFunSvc.findMpsRoleFuns(map);
            return mpsRoleFunAuths;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mpsRoleFunAuths;
    }

    public List<MpsRoleOpt> getOptById(String roleId) {
          /*
        依据roleId获取功能权限id
        */
        List<MpsRoleOpt> mpsRoleOptAuths = null;
        try {
            //构建条件查询
            Map<String, Object> map = new HashMap<>();
            Condition condition = new Condition();
            condition.setConnector("and");
            condition.setColumn("roleId");
            condition.setOperator("=");
            condition.setType("S");
            condition.setValue(roleId);
            List<Condition> conditions = new ArrayList<>();
            conditions.add(condition);
            map.put("conditions", conditions);
            //依据关联表查询该角色拥有的功能权限
            mpsRoleOptAuths = mpsRoleOptSvc.findMpsRoleOpts(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mpsRoleOptAuths;
    }


}
